package com.hankol.material.fragment

import androidx.lifecycle.Observer
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseFragment
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.bean.download.ShowUIUtils
import com.baselibrary.db.DBManager
import com.baselibrary.manager.LoadingManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.HKUtils
import com.baselibrary.utils.SpUtils
import com.baselibrary.utils.ToastUtils
import com.hankol.material.MaterialMainHomeActivity
import com.hankol.material.R
import com.hankol.material.adapter.HomeFolderListAdapter
import com.hankol.material.api.MaterialConstants
import com.hankol.material.bean.CreateFolderBean
import com.hankol.material.bean.FolderListBean
import com.hankol.material.databinding.FragmentHomeFolderBinding
import com.hankol.material.viewmodel.HomeFolderViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**素材库首页--收藏夹列表
 * @time: 2021/11/15 10:01
 * @description:
 */
class HomeFolderFragment : BaseFragment() {
    private lateinit var mViewModel: HomeFolderViewModel
    private lateinit var dataBinding: FragmentHomeFolderBinding
    private lateinit var mHomeFolderListAdapter: HomeFolderListAdapter
    private var listBeans: List<FolderListBean>? = null

    companion object {
        fun newInstance(): HomeFolderFragment {
            return HomeFolderFragment()
        }
    }

    override fun init() {

        mViewModel = getFragmentViewModelProvider(this).get(HomeFolderViewModel::class.java)
        dataBinding = getDataBinding<FragmentHomeFolderBinding>()

        mHomeFolderListAdapter = HomeFolderListAdapter(activity as MaterialMainHomeActivity, mViewModel)
        dataBinding.rvHomeFolder.adapter = mHomeFolderListAdapter
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initListener()
        initObserve()
        mViewModel.getFolderList()
    }

    //显示下载的数量
    fun showDownloadingCnt() {
        val downloadList = DBManager.getInstance().getDownloadList(userIds, true)
        val list = mutableListOf<DownloadInfo>()
        for (info in downloadList) {
            if (info.downloadStatus == DownloadInfo.DOWNLOAD || info.downloadStatus == DownloadInfo.DOWNLOAD_PAUSE || info.downloadStatus == DownloadInfo.DOWNLOAD_WAIT)
                list.add(info)
        }
        if (list.size > 0) {
            dataBinding.tvDownloadingCnt.text = "${ShowUIUtils.showFormatCnt(list.size)}"
        } else {
            dataBinding.tvDownloadingCnt.text = ""
        }
    }

    private fun initObserve() {
        mViewModel.folderListResultBean.observe(this, Observer {
            hideLoadingDialog()
            listBeans = it
            if (it.isNullOrEmpty()) {
                //还没有创建文件，先创建默认文件夹
                mViewModel.createFolder(MaterialConstants.DEF_FOLDER_NAME)
            } else {
                //已有文件夹
                mHomeFolderListAdapter.setData(it)
            }
        })

        mViewModel.deleteFolderResultBean.observe(this, Observer {
            LoadingManager.hideLoadingDialog(activity)
            if (it) {
                //删除成功
                mHomeFolderListAdapter.deleteItemData()
                ToastUtils.showShort(context, "文件夹已删除")
            } else {
                //删除失败
                ToastUtils.showShort(context, "文件夹删除失败")
            }
        })

        val observer = Observer<CreateFolderBean> { it ->
            if (it == null) return@Observer
            mHomeFolderListAdapter.setData(mViewModel.handlerData(it))
            mViewModel.createResultBean.removeObserver { it }
        }

        mViewModel.createResultBean.observe(this, observer)
    }

    private fun initListener() {
        dataBinding.rlHomeFolderDownload.setOnClickListener {
            if (!HKUtils.isFastClick()) return@setOnClickListener
            //进入我的下载
            ActivityRouter.startActivity(ActivityRouter.MATERIAL.MATERIAL_DOWNLOAD_MAIN)
        }

    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home_folder
    }

    val userIds: Int by lazy { SpUtils.getInstance().userId }

    //EventBus 接受方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgId_material_createFolder) {
            /*val mList: ArrayList<FolderListBean> = arrayListOf()
            mList.add(messageBus.param1 as FolderListBean)
            mHomeFolderListAdapter.addData(mList)*/
            showLoadingDialog()
            mViewModel.getFolderList()
        } else if (messageBus.codeType == MessageBus.msgId_material_upFolder) {
            mHomeFolderListAdapter.upItemData(messageBus.param1 as FolderListBean)
        } else if (messageBus.codeType == MessageBus.msgid_start_download || messageBus.codeType == MessageBus.msgId_del_material_file) {
            showDownloadingCnt()
        }
    }

    override fun onResume() {
        super.onResume()
        showDownloadingCnt()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD_OVER == info.downloadStatus) {
            showDownloadingCnt()
        }
    }

}
